var myOptions=new Object();
var pastDecisions = {}; // hash object
var DEBUG = false;  // true == verbose mode
/*The code contained inside this block will be moved to a stand alone .js file*/
   function IntelliForm(){
      this.myform=myform;//the form name
      this.myelements=formelements;//the form element names in an array
      this.initialize();
	 
      setupHistory(this.myform, this.myelements);
	  initHistory(this.myform, this.myelements);
      //saveOptions(this.myform, this.myelements);
}

	/* gets elements regardless of browser 
	   for future IE compatability    */
	function getel(id) {
  		if (document.getElementById) {
    		return document.getElementById(id);
  		} else if (window[id]) {
    		return window[id];
  		}
  		return null;
	}



IntelliForm.prototype = {
	initialize: function(){
      for(x=0;x<this.myelements.length;x++){
        this.addEvent(this.myelements[x],'onchange', function(){myonchange(this);});
      }//adds onchange event to each intelligent element in the form 
      this.addEvent(this.myform,'onsubmit', myonsubmit); //add onsubmit event to retrieve search results
	},
 	addEvent: function(el,event,func){
	/*
	  *This code attaches an event to an html element
	  *Eventually will be replaced by cross-browser script
	  *Currently will only work on Non-IE browsers
	*/
		//alert('initializing this element:'+el);
	 	document.getElementById(el)[event]=func;
	}
}; 


	function myonchange(formEl){
	/*
	 * This function sends the Ajax request after
	 * a form element has been altered.
	*/
	
	   var myId=formEl.getAttribute('id');
	   var myVal=document.getElementById(myId).value;
	
	   var needReload = false;
	   var addToEnd = false;
	   var temp= {};
	   /* go through history */
       if (myId in pastDecisions)
       {
	       // updated something already in history
	       if (pastDecisions[myId]==myVal) 
	       {
			 // alert("Re-selected same value of previous decision.");
			 return;
	       } else if (myVal) {
              //alert("Changed value of previous decision:"+myVal+'.');
              var found=false;
              for (i=0; i<myOptions.savedElement.length; i++)
              {
	             if(myOptions.savedElement[i]==myId)
	             {
		             found = true;
		             temp[myId] = myId;
		             addToEnd = true;

	             } else if (found) {
		             // remove everything else after 
	                 temp[myOptions.savedElement[i]]=myOptions.savedElement[i];
	             }
	             
	
			  }
			  needReload = true;
           } else {
	         // alert("Changed value of previous decision to null."+myOptions.savedElement.size);
              var found=false;
              for (i=0; i<myOptions.savedElement.length; i++)
              { 
	 
	             if(myOptions.savedElement[i]==myId)
	             {
		             found = true;
		             temp[myId]=myId;
	             } else if (found) {
		             // remove everything else after 
	                  temp[myOptions.savedElement[i]]=myOptions.savedElement[i];
	             }
	             
	
			  }
			  needReload = true;
	       }
       } else {
          addHistory(myId);
          //needReload = true;
       }


       /* if something's really changed, call update */
       if (needReload)
	   {
		
	     for(t in temp)
	    {
		       removeHistory(temp[t]);
		       
	     }
	     if (addToEnd) { addHistory(myId); }
		
		  //need to remove everything after a point
		// pastDecisions = {};
 		// myOptions.savedElement=new Array(1);
	  	// myOptions.savedSelection=new Array(1);
		 //initHistory(this.myform, this.formelements) 

       }

       if (DEBUG){
	     var outString = "History: ";
	     for (k in pastDecisions)
         {
	         outString+="("+k+","+pastDecisions[k]+") ";
	     }
	     alert(outString);
       }
	   requestFunction( 'update' , pastDecisions );
	}
	
	function myonsubmit(id){
	/*
	 * This function submits all the form information to the server.
	 */
	

	  var QS=document.forms[this.myform];
	  requestFunction( 'search' , QS );
	}

	function myresponse(result){
	/*
	 * this function analyzes the XML document returned by the 
	 * Ajax response function and updates the relevant form fields
	 */
	
	
	   // initially hide all forms
		for(x=0; x< formelements.length;x++){
   			var myelement=formelements[x];
            // except ones that are select (those are neglected in the xml response)
            if (myelement in pastDecisions) { continue; }
            for(c=0; c<document.forms[myform].elements[myelement].options.length; c++) {
   			    document.forms[myform].elements[myelement].options[c].style.display = 'none'; //.setAttribute('disabled','disabled');
            }
        }
		var step1=result.getElementsByTagName('formelement');
	 	for(x=0;x<step1.length;x++){
	 		  //alert(result.getElementsByTagName('formelement').length);
              var myname=result.getElementsByTagName('formelement')[x].getAttribute('name');
              //alert(myname);
          	  var step2=step1[x].getElementsByTagName('option');
       
              for(y=0; y<step2.length;y++){
             	//alert(result.getElementsByTagName('formelement')[x].getElementsByTagName('option').length);
             	var myvalue=step2[y].firstChild.data; 
                // redisplay options
				
                if (myvalue == "null") {
		           if (step2.length >1) // don't display null record unless > 1 options
                      document.forms[myform].elements[myname].options[0].style.display = '';
                } else {       
			  	   if (document.forms[myform].elements[myname].options[myvalue])
			            document.forms[myform].elements[myname].options[myvalue].style.display = ''; 
			       else
						alert("Error, undefined "+myname+' '+myvalue);
				}
				if (step2.length==2 && myvalue != "null") {
			         document.forms[myform].elements[myname].selectedIndex=myvalue;
		             addHistory(myname);
		        }
              } // end for
          
            
        } 
		var recordcount = result.getElementsByTagName('totalRecords')[0].firstChild.nodeValue;
		var searchString = "Show me "+recordcount.replace(/^\s*/, '').replace(/\s*$/, '')+" restaurants";
		document.forms[myform].elements['submit'].value=searchString;

	}

        function replaceOption(element, opNo, mytext, myvalue){
         /*
	*  this function replaces the option for the specified form element
	*
	*/ 
	
			document.forms[myform].elements[element].options[opNo]= new Option(mytext, myvalue);
        }

 	function getValues(){
   		var myValues=new Object();
   		for(x=0; x< formelements.length;x++){
   			var myelement=formelements[x];
   			myValues[myelement]=document.forms[myform].elements[myelement].value;
   		}
   
   		return myValues;
   	}
  
  function getOption(myelement, myvalue){
 // 	alert(myelement+'<--element  value--->'+myvalue);
  	for(x=0;x<myOptions[myelement].length;x++){
  		if( myOptions[myelement][x][2] == myvalue ){
	  		var thisValue = myOptions[myelement][x][1];
	  		break;
	  	}
  	}
  	return thisValue
  }
  

  function setupHistory(){
  	myOptions.savedElement=new Array(1);
  	myOptions.savedSelection=new Array(1);

    
  	//saveOptions(arguments[0],arguments[1]);

 }
  
  function removeHistory(element) {
	delete (pastDecisions[element]);  // remove from history hash
	 
	// remove from option arrays
	var i =0;
	for ( ; i< myOptions.savedElement.length && element!=myOptions.savedElement[i]; i++ ) { ; }
	myOptions.savedElement.splice(i,1);
	myOptions.savedSelection.splice(i,1);
	
	// update form

     for (i=0; i<document.getElementById(element).options.length; i++)
         document.getElementById(element).options[i].style.display = '';

	 document.getElementById(element).selectedIndex=0;
  }

    
  function addHistory(thiselement){
  		var arrayNum=myOptions.savedElement.length;
  		myOptions.savedElement[arrayNum]=thiselement;
        
        
		if(!document.getElementById(thiselement))
		{
			alert("Error: Couldn't get element: "+thiselement);
			return;
		}
		//alert("Got element: "+thiselement);
	    myOptions.savedSelection[arrayNum]=document.getElementById(thiselement).value;
        pastDecisions[thiselement]=document.getElementById(thiselement).value;
  }
  
  /* only save selected options */
  function initHistory(myform, myelements){
	 for (x=0; x<myelements.length; x++ ) {
		var val = document.forms[myform].elements[myelements[x]].value;
		if (val != "")
		{	
			//alert("No-null value at "+val);
			id=document.forms[myform].elements[myelements[x]].getAttribute('id');
			//alert(id);
			addHistory(id);
		}
	}	
  }

  function saveOptions(myform, myelements){
  	for(x=0;x<myelements.length;x++){
  		myOptions[myelements[x]]=new Array(1);
  		for(y=0;y<document.forms[myform].elements[myelements[x]].options.length;y++){
  			myOptions[myelements[x]][y]= new Array(1);
  			myOptions[myelements[x]][y][1]=document.forms[myform].elements[myelements[x]].options[y].text;
  			//alert(myOptions[myelements[x]][y][1]);
  			myOptions[myelements[x]][y][2]=document.forms[myform].elements[myelements[x]].options[y].value;
  			//alert(myOptions[myelements[x]][y][2]);
  		}
  	}
  	
  }


